"""
Test configuration for Emobot API
"""
import tests
import os
import sys
from unittest.mock import Mock, patch
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool

# Add the project root to the Python path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import app
from db.connection import Base
from services.conversation import ConversationService
# 云侧人脸识别已禁用
# from services.face_recognition import FaceRecognitionService
from services.user import UserService
from services.prompt import PromptService

# Test database setup
TEST_DATABASE_URL = "sqlite:///:memory:"
TEST_REDIS_URL = "redis://192.168.5.93:6379/1"


@pytest.fixture(scope="session")
def test_db_engine():
    """Create a test database engine"""
    engine = create_engine(
        TEST_DATABASE_URL,
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    Base.metadata.create_all(bind=engine)
    yield engine
    Base.metadata.drop_all(bind=engine)


@pytest.fixture
def test_db_session(test_db_engine):
    """Create a test database session"""
    TestingSessionLocal = sessionmaker(
        autocommit=False, autoflush=False, bind=test_db_engine
    )
    session = TestingSessionLocal()
    try:
        yield session
    finally:
        session.close()


@pytest.fixture
def test_client():
    """Create a test client for FastAPI app"""
    return TestClient(app)


@pytest.fixture
def mock_redis():
    """Mock Redis service"""
    with patch("cache.redis.cache_service") as mock_redis:
        mock_redis.get.return_value = None
        mock_redis.set.return_value = True
        yield mock_redis


@pytest.fixture
def mock_vlm_api():
    """Mock VLM API responses"""
    with patch("services.conversation.requests.post") as mock_post:
        mock_response = Mock()
        mock_response.json.return_value = {"response": "Test response from VLM"}
        mock_response.raise_for_status.return_value = None
        mock_post.return_value = mock_response
        yield mock_post


# 云侧人脸识别已禁用
# @pytest.fixture
# def mock_face_recognition():
#     """Mock face recognition service"""
#     with patch("services.face_recognition.FaceRecognitionService") as mock_class:
#         mock_instance = Mock()
#         mock_instance.process_image_for_face_recognition.return_value = {
#             "user_id": "test_user_123",
#             "face_detected": True,
#             "confidence": 0.85,
#         }
#         mock_instance.detect_faces.return_value = [(0, 0, 100, 100)]
#         mock_instance.get_largest_face_embedding.return_value = [0.1] * 512
#         mock_class.return_value = mock_instance
#         yield mock_instance


@pytest.fixture
def fake_user_data():
    """Fake user data for testing"""
    return {
        "user_id": "test_user_123",
        "name": "Test User",
        "age": 25,
        "gender": "male",
    }


@pytest.fixture
def fake_conversation_data():
    """Fake conversation data for testing"""
    return {
        "user_id": "test_user_123",
        "session_id": "test_session_456",
        "message": "Hello, how are you?",
        "image_url": None,
        "intent": "greeting",
    }


@pytest.fixture
def fake_image_data():
    """Fake image data for testing"""
    return {
        "filename": "test_face.jpg",
        "content": b"fake_image_content",
        "content_type": "image/jpeg",
    }


@pytest.fixture
def conversation_service(test_db_session, mock_redis, mock_vlm_api):
    """Create a conversation service with mocked dependencies"""
    return ConversationService(test_db_session)


@pytest.fixture
def user_service(test_db_session):
    """Create a user service"""
    return UserService(test_db_session)


@pytest.fixture
def prompt_service():
    """Create a prompt service"""
    return PromptService()


# 云侧人脸识别已禁用
# @pytest.fixture
# def face_recognition_service():
#     """Create a face recognition service"""
#     return FaceRecognitionService()


# Environment variables for testing
@pytest.fixture(autodoc=True)
def test_env_vars():
    """Set test environment variables"""
    original_env = {}
    test_vars = {
        "DATABASE_URL": TEST_DATABASE_URL,
        "REDIS_URL": TEST_REDIS_URL,
        "VLM_API_URL": "http://test-vlm-api:8000",
        "VLM_API_KEY": "test-api-key",
        "LOG_LEVEL": "DEBUG",
    }

    # Save original environment
    for key in test_vars:
        original_env[key] = os.environ.get(key)
        os.environ[key] = test_vars[key]

    yield test_vars

    # Restore original environment
    for key, value in original_env.items():
        if value is None:
            os.environ.pop(key, None)
        else:
            os.environ[key] = value
